import { onMounted, onUnmounted, ref, type Ref } from 'vue'
import { throttle } from 'underscore'

export  function useScroll(elRef?: Ref<HTMLElement | undefined>) {
  // el 可能是 window 或 HTMLElement
  let el: Window | HTMLElement = window

  const isReachBottom = ref(false)

  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)

  // 防抖/节流
  const scrollListenerHandler = throttle(() => {
    if (el === window) {
      clientHeight.value = document.documentElement.clientHeight
      scrollTop.value = document.documentElement.scrollTop
      scrollHeight.value = document.documentElement.scrollHeight
    } else {
      clientHeight.value = (el as HTMLElement).clientHeight
      scrollTop.value = (el as HTMLElement).scrollTop
      scrollHeight.value = (el as HTMLElement).scrollHeight
    }
    if (clientHeight.value + scrollTop.value >= scrollHeight.value) {
      // console.log("滚动到底部了")
      isReachBottom.value = true
    } else {
      isReachBottom.value = false
    }
  }, 100)

  onMounted(() => {
    if (elRef && elRef.value) el = elRef.value
    el.addEventListener('scroll', scrollListenerHandler)
  })

  onUnmounted(() => {
    el.removeEventListener('scroll', scrollListenerHandler)
  })

  return { isReachBottom, clientHeight, scrollTop, scrollHeight }
}
